package com.sf.tools.ui;

import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ColorChooser implements ActionListener{

	private JPanel con = new JPanel();

	private JButton colorBtn = new JButton("点击获取颜色");
	private JLabel label1 = new JLabel("R:");
	private JTextField text1 = new JTextField();
	private JLabel label2 = new JLabel("G:");
	private JTextField text2 = new JTextField();
	private JLabel label3 = new JLabel("B:");
	private JTextField text3 = new JTextField();
	
	private JLabel label4 = new JLabel("16进制:");
	private JTextField text4 = new JTextField();
	
	private Color color = new Color(0, 0, 0);
	private JLabel label5 = new JLabel("预览:");
	private JPanel cPanel = new JPanel();
	
	private JDialog jd;
	private JColorChooser jcc=new JColorChooser();
	
	public ColorChooser(){
		colorBtn.setBounds(230, 50, 120, 20);
		
		label1.setBounds(100, 50, 15, 20);
		text1.setBounds(120, 50, 100, 20); text1.setEditable(false);
		
		label2.setBounds(100, 80, 15, 20);
		text2.setBounds(120, 80, 100, 20); text2.setEditable(false);
		
		label3.setBounds(100, 110, 15, 20);
		text3.setBounds(120, 110, 100, 20); text3.setEditable(false);
		
		label4.setBounds(70, 140, 45, 20);
		text4.setBounds(120, 140, 100, 20); text4.setEditable(false);
		
		label5.setBounds(70, 170, 45, 20);
		cPanel.setBounds(120, 170, 120, 50);
		
		colorBtn.addActionListener(this);
		
		con.setLayout(null);
		con.add(colorBtn);
		con.add(label1);
		con.add(text1);
		con.add(label2);
		con.add(text2);
		con.add(label3);
		con.add(text3);
		con.add(label4);
		con.add(text4);
		con.add(label5);
		con.add(cPanel);
		
		
		jd=JColorChooser.createDialog(con,"选择颜色",true,jcc,this,null);
		Image frame_icon=Toolkit.getDefaultToolkit().createImage(getClass().getResource("/flashget.png"));
		jd.setIconImage(frame_icon);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(colorBtn)){
			//设置颜色选择器的颜色
			jcc.setColor(color);
			//设置颜色选择器可见
			jd.setVisible(true);
		}else{
			color=jcc.getColor();
			cPanel.setBackground(color);
			
			text1.setText("Red: " + color.getRed());
			text2.setText("Green: " + color.getGreen());
			text3.setText("Blue: " + color.getBlue());
			String hex = rgb2hex(color.getRed(),color.getGreen(),color.getBlue());
			text4.setText(hex);
		}
	}
	private final static String[] HEX = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
	public String rgb2hex(int r,int g,int b){
//		System.out.println(HEX[r/16] + HEX[r%16] + HEX[g/16] + HEX[g%16] + HEX[b/16] + HEX[b%16]);
		return HEX[r/16] + HEX[r%16] + HEX[g/16] + HEX[g%16] + HEX[b/16] + HEX[b%16];
	}
	
	public Container getCon() {
		return con;
	}
}
